import pandas as pd
import easyquotation,os
try:
    quotation = easyquotation.use('tencent')
except:
    quotation = easyquotation.use('sina')

def tencentQuo(OQ代码,价格类型):
    # 获取委托价格
    # print(OQ代码)
    if ".SH" in OQ代码:
        腾讯代码="sh"+OQ代码[0:6]
    elif ".SZ" in OQ代码:
        腾讯代码="sz"+OQ代码[0:6]
    try:
        价格=quotation.real(腾讯代码)[腾讯代码[2:8]][价格类型]
    except Exception as e:
        print(e)
        价格=0
    return 价格
# 指定文件夹路径
folder_path = '.'

# 获取所有文件
files = os.listdir(folder_path)

# 筛选出以 'positionInfo' 开头的 CSV 文件
csv_files = [f for f in files if f.startswith('positionInfo') and f.endswith('.csv')]

持仓文件=csv_files[0]
持仓=pd.read_csv(持仓文件,index_col=0, encoding='GB2312')
for index,row in 持仓.iterrows():
    最新价=tencentQuo(row["securityID"],"now")
    if 最新价==0:
        print(f"{row['securityID']}获取最新价失败，请检查腾讯行情接口")
    持仓.loc[index,"最新价"]=最新价
    持仓.loc[index,"持仓市值"]=最新价*row["当前数量"]

持仓.to_csv(r".\positionInfo_new.csv",index=False)
print("已按当前最新价重算持仓的最新价和市值")
